package com.gywj.race.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gywj.race.config.exception.BaseException;
import com.gywj.race.dto.GetPatchNumberBookDataDto;
import com.gywj.race.mapper.EventInformationMapper;
import com.gywj.race.mapper.ExpandMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class DownloadAllNumberBookService {

    @Resource
    private EventInformationMapper eventInformationMapper;
    @Resource
    private ExpandMapper expandMapper;

    public void downloadAllNumberBookByEventId(GetPatchNumberBookDataDto getPatchNumberBookDataDto, HttpServletResponse response) throws Exception {

        List<Map<String, Object>> patchNumberBookData = expandMapper.getPatchNumberBookData(getPatchNumberBookDataDto);
        if (!CollectionUtils.isEmpty(patchNumberBookData)) {
            List<Map<String, Object>> fileList = Lists.newArrayList();
            patchNumberBookData.forEach(dataMap -> {
                String code = (String) dataMap.get("participantCode");
                String name = (String) dataMap.get("name");
                String eventGroupName = (String) dataMap.get("groupName");
                Color color = new Color(255, 80, 84);
                if (eventGroupName.equals("半程马拉松(21.0975KM)")) {
                    color = new Color(110, 187, 235);
                }
                if (eventGroupName.equals("全程马拉松(42.195KM)")) {
                    color = new Color(206, 54, 209);
                }

                String numberbook = (String) dataMap.get("numberbook");
                BufferedImage imageLocal = null;

                try {
                    imageLocal = ImageIO.read(new URL(numberbook));
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BaseException(e.getMessage());
                }
                Graphics2D g = imageLocal.createGraphics();
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                Font font = new Font("微软雅黑", Font.BOLD, 190 * 6);
                g.setFont(font);
                g.setColor(color);
                g.drawString(code, 380 * 6, 400 * 6);

                Graphics2D g1 = imageLocal.createGraphics();
                g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g1.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
                g1.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                Font font1 = new Font("微软雅黑", Font.BOLD, 80 * 6);
                g1.setFont(font1);
                g1.setColor(color);
                if (name.length() > 3) {
                    g1.drawString(name, 50 * 6, 385 * 6);
                } else if (name.length() == 3) {
                    g1.drawString(name, 75 * 6, 385 * 6);
                } else {
                    g1.drawString(name, 100 * 6, 385 * 6);
                }


                g.dispose();
                g1.dispose();
                String path = "";

                try {
                    path = this.getClass().getResource("/").toURI().getPath() + "static/" + code + ".jpg";
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                    throw new BaseException(e.getMessage());
                }

                Map<String, Object> fileMap = Maps.newHashMap();
                try {
                    ImageIO.write(imageLocal, "jpg", Files.createFile(Paths.get(path)).toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BaseException(e.getMessage());
                }
                fileMap.put("path", path);
                fileMap.put("filename", code + ".jpg");
                fileList.add(fileMap);
            });

            //开始时间
            response.setContentType("application/x-zip-compressed");
            response.setHeader("Content-disposition", "attachment;filename=numberbook.zip");
            OutputStream out = response.getOutputStream();
            long start = System.currentTimeMillis();
            zipFilePatch(fileList, out);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
            // 删除中间文件
            for (Map<String, Object> ma : fileList) {
                Files.delete(Paths.get(String.valueOf(ma.get("path"))));
            }
        } else {
            throw new BaseException("暂无数据");
        }

    }

    private void zipFilePatch(List<Map<String, Object>> fileList, OutputStream out) {
        try (ZipOutputStream zipOut = new ZipOutputStream(out);
             WritableByteChannel writableByteChannel = Channels.newChannel(zipOut)) {
            for (Map<String, Object> ma : fileList) {
                try (FileChannel fileChannel = new FileInputStream(String.valueOf(ma.get("path"))).getChannel()) {
                    zipOut.putNextEntry(new ZipEntry(String.valueOf(ma.get("filename"))));
                    fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
                    zipOut.closeEntry();
                }
            }
            zipOut.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void downloadNumberBookNoNameBm(HttpServletResponse response) throws Exception {
        String bm = "http://gywj-race.oss-cn-beijing.aliyuncs.com/img/AE73FAFCADAC41DA9AA5589C33300E82.jpg";
        List<String> bmcode = Lists.newArrayList();
        bmcode.add("H880");
        bmcode.add("H881");
        bmcode.add("H882");
        bmcode.add("H883");
        bmcode.add("H885");
        bmcode.add("H886");
        Color bmcolor = new Color(110, 187, 235);
        List<Map<String, Object>> bmfileList = Lists.newArrayList();
        createNumberBookPatch(bm, bmcode, bmcolor, bmfileList);
        //开始时间
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-disposition", "attachment;filename=numberbook.zip");
        OutputStream out = response.getOutputStream();
        long start = System.currentTimeMillis();
        zipFilePatch(bmfileList, out);
        long end = System.currentTimeMillis();
        System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        // 删除中间文件
        for (Map<String, Object> ma : bmfileList) {
            Files.delete(Paths.get(String.valueOf(ma.get("path"))));
        }
    }


    public void downloadNumberBookNoNameQm(HttpServletResponse response) throws Exception {
        String bm = "http://gywj-race.oss-cn-beijing.aliyuncs.com/img/D6BB3FDAF6F4461C9A0F29BD6556DFAD.jpg";
        List<String> bmcode = Lists.newArrayList();
        bmcode.add("M880");
        bmcode.add("M881");
        bmcode.add("M882");
        bmcode.add("M883");
        bmcode.add("M885");
        bmcode.add("M886");
        Color bmcolor = new Color(206, 54, 209);
        List<Map<String, Object>> bmfileList = Lists.newArrayList();
        createNumberBookPatch(bm, bmcode, bmcolor, bmfileList);
        //开始时间
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-disposition", "attachment;filename=numberbook.zip");
        OutputStream out = response.getOutputStream();
        long start = System.currentTimeMillis();
        zipFilePatch(bmfileList, out);
        long end = System.currentTimeMillis();
        System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        // 删除中间文件
        for (Map<String, Object> ma : bmfileList) {
            Files.delete(Paths.get(String.valueOf(ma.get("path"))));
        }
    }

    private void createNumberBookPatch(String bm, List<String> bmcode, Color bmcolor, List<Map<String, Object>> bmfileList) throws IOException, URISyntaxException {
        for (String aBmcode : bmcode) {
            BufferedImage readbm = ImageIO.read(new URL(bm));
            Graphics2D g = readbm.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Font font = new Font("微软雅黑", Font.BOLD, 190 * 6);
            g.setFont(font);
            g.setColor(bmcolor);
            g.drawString(aBmcode, 200 * 6, 400 * 6);
            g.dispose();
            String bmpath = this.getClass().getResource("/").toURI().getPath() + "static/" + aBmcode + ".jpg";
            ImageIO.write(readbm, "jpg", Files.createFile(Paths.get(bmpath)).toFile());
            Map<String, Object> fileMap = Maps.newHashMap();
            fileMap.put("path", bmpath);
            fileMap.put("filename", aBmcode + ".jpg");
            bmfileList.add(fileMap);
        }
    }
}
